package com.itheima.reggie.fifter;

import cn.hutool.core.text.AntPathMatcher;
import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.MyThreadLocal;
import com.itheima.reggie.common.R;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter(filterName = "loginFifter", urlPatterns = "/*")
public class LoginFifter implements Filter {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 进行业务操作前校验是否登录,未登录返回登录界面
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();
        String[] patterns = {"/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg"};
        for (String pattern : patterns) {
            if (antPathMatcher.match(pattern, requestURI)) {
                filterChain.doFilter(request, response);
                return;
            }
        }
        Long loginUser = (Long) request.getSession().getAttribute("employee");
        if (loginUser != null) {
            MyThreadLocal.set(loginUser);
            filterChain.doFilter(request, response);
            MyThreadLocal.remove();
            return;
        }
        //判断User登录状态，如果已登录，则直接放行
        if(request.getSession().getAttribute("user") != null){

            Long userId = (Long) request.getSession().getAttribute("user");
            MyThreadLocal.set(userId);
            filterChain.doFilter(request,response);
            MyThreadLocal.remove();
            return;
        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }
}
